package com.hmdp.exception;

import com.hmdp.asserts.Asserts;
import com.hmdp.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * date: 2023/9/9 12:14
 * author: MR.孙
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler({BusinessException.class})
    public Result businessExceptionHandler(BusinessException businessException) {
        String message = businessException.getMessage();
        Object data = businessException.getData();
        if (data instanceof Asserts) {
            // 如果是 Asserts 抛出的异常, 那就直接使用 Result 包装下返回
            Asserts asserts = (Asserts) data;
            String assertsMsg = asserts.getMsg();
            String actualMessage = message.equals(assertsMsg) ? assertsMsg : assertsMsg + " " + message;
            return Result.fail(actualMessage);
        }

        return Result.fail(businessException.getMessage());

    }

    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e) {
        log.error(e.toString(), e);
        return Result.fail("服务器异常");
    }

    @ExceptionHandler({Exception.class})
    public Result exceptionHandler(Throwable t) {
        logger.warn("出现未知异常", t);
        return Result.fail(Asserts.FAILURE.msg);
    }



}
